from django.views import View
import jwt
from app.models import *
import uuid
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
import base64
import requests
from Crypto.Cipher import AES
from utils.RandomNumber import randomNumber

# 你的微信小程序的 appid 和 appsecret
APP_ID = 'wx2707919ba87928c7'
APP_SECRET = 'c7d0be0397d6dda20747e4ebba8085d3'


def get_session_key(code):
    url = 'https://api.weixin.qq.com/sns/jscode2session'
    params = {
        'appid': APP_ID,
        'secret': APP_SECRET,
        'js_code': code,
        'grant_type': 'authorization_code'
    }
    response = requests.get(url, params=params)
    return response.json()


@csrf_exempt
def decrypt_phone(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            encrypted_data = data.get('encryptedData')
            iv = data.get('iv')
            code = data.get('code')

            if not encrypted_data or not iv or not code:
                return JsonResponse({'error': 'Missing parameters'}, status=400)

            session_key_response = get_session_key(code)
            session_key = session_key_response.get('session_key')

            if not session_key:
                return JsonResponse({'error': 'Failed to get session_key'}, status=500)

            # Base64 decode
            encrypted_data = base64.b64decode(encrypted_data)
            iv = base64.b64decode(iv)
            session_key = base64.b64decode(session_key)

            # Decrypt
            cipher = AES.new(session_key, AES.MODE_CBC, iv)
            decrypted = cipher.decrypt(encrypted_data)

            # Remove padding
            pad_length = decrypted[-1]
            decrypted = decrypted[:-pad_length]

            # Convert to string and parse JSON
            decrypted_str = decrypted.decode('utf-8')
            result = json.loads(decrypted_str)
            phone_number = result.get('phoneNumber')

            return {'phoneNumber': phone_number}

        except Exception as e:
            return {'error': str(e), 'er': '11'}

    return {'error': 'Invalid request method'}


class LoginView(View):
    def post(self, request):
        try:
            # 获取解密后的手机号
            phone = decrypt_phone(request)
            # 参数错误处理
            if not phone.get('phoneNumber'):
                return JsonResponse({
                    'code': 400,
                    'msg': '获取手机号失败！'
                })
            # 获取用户手机号
            phone = phone.get('phoneNumber')
            # 创建token内信息
            paylod = {'phone': phone}
            # 生成token
            token = jwt.encode(payload=paylod, key='IAmGreat')
            # 生成一个唯一值用作id
            unique_id = str(uuid.uuid4())
            # 查询用户是否存在
            user = User.objects.filter(phone=phone).first()
            # 如果用户存在，则跳过添加
            if not user:
                # 将用户手机号添加到数据库
                _id = uuid.uuid4()
                UserProfile.objects.create(id=_id, IDCode=randomNumber())  # 创建用户信息表
                Gold.objects.create(id=_id)  # 创建用户对应金币表
                User.objects.create(phone=phone, id=_id, is_locked=False, userinfo_id=_id, gold_id=_id)
            # 查询用户信息
            user = User.objects.filter(phone=phone).first()
            # 数据库查询该手机号是否已被锁定
            if user.is_locked:
                return JsonResponse({
                    'code': 403,
                    'msg': '您的帐号已被锁定，请联系客服解锁'
                })
            # 登录成功返回token并返回到前台
            return JsonResponse({
                'code': 200,
                'msg': '登录成功',
                'data': {
                    "token": token.decode('utf-8'),
                    "id": user.id,
                    "phone": user.phone
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': str(e)
            })
